var _CONFIG = {
    TYPE: 'Web',
    JQXGRID: '#jqx_grid_view',
    BINDING_URI: base_url + 'cms/cp/menu/binding/',
    EDITPANEL_URI: base_url + 'cms/cp/menu/editpanel/',
    COMMIT_URI: base_url + 'cms/cp/category/commit/',
    DELETE_URI: base_url + 'cms/cp/category/delete/'
};
var _CP = (function() {
    var oTable;
    var that = this;
    var datafields = [
        {name: 'Id', type: 'int'},
        {name: 'Thumb'},
        {name: 'Title'},
        {name: 'Display'},
        {name: 'ParentTitle'},
        {name: 'Parent', type: 'int'},
        {name: 'Type'}, {name: 'Level', type: 'int'},
        {name: 'Position', type: 'int'},
        {name: 'Active', type: 'bool'},
        {name: 'Insert', type: 'date'},
        {name: 'Update', type: 'date'},
    ];
    var source, dataAdapter;
    return {
        onCommit: function(Params, Id, callback) {
            /* Commit data lên vào DB, Id>0 là Update, Id=0 hoặc ko có là Insert */
            backend({
                url: _CONFIG.COMMIT_URI,
                data: {
                    Id: Id,
                    Params: Params
                },
                callback: function(rsdata) {
                    if (rsdata.result < 0) {
                        $.jGrowl(rsdata.message, {sticky: true, theme: 'growl-error', header: 'Error!'});
                    } else {
                        $.jGrowl(rsdata.message);
                        if (typeof callback == 'function') {
                            callback();
                        }
                    }
                }
            }).call();
        },
        creategrid: function() {

            source = {
                datatype: "json", type: "POST",
                datafields: datafields,
                url: _CONFIG.BINDING_URI + _CONFIG.TYPE,
                hierarchy:
                        {
                            keyDataField: {name: 'Id'},
                            parentDataField: {name: 'Parent'}
                        },
                id: 'Id',
                root: 'rows',
            };
            dataAdapter = new $.jqx.dataAdapter(source, {
                loadError: function(xhr, status, error) {
                    bckdialog({type: 'error'}).open("<b>Status</b>:" + xhr.status + "<br/><b>ThrownError</b>:" + error + "<br/>", 'Error Message!');
                }
            });
            var columns = [
                {
                    text: '', dataField: 'Id', width: 60, filterable: false, sortable: false, editable: false,
                    cellsrenderer: function(row, columnfield, value, defaulthtml, columnproperties) {
                        var str = "";
                        if (value && value > 0) {
                            try {
                                //value = $.parseJSON(value);
                                str += "\
                                    <span style='margin: 4px 4px 4px 12px; float: left;' class=\"icon-pencil\" onclick=\"_CP.onEditItem(" + value + ");\"  title='Edit:" + value + "'></span>\
                                ";
                                str += "\
                                    <span style='margin: 4px; float: left;' class='icon-trash' onclick=\"_CP.onDeleteItem(" + value + ");\" title='Delete:" + value + "'></span>\
                                ";
                            } catch (e) {
                            }
                        }

                        return str;
                    }
                },
                {
                    text: 'Title', dataField: 'Title', minWidth: 220,
                    cellsrenderer: function(row, columnfield, value, defaulthtml, columnproperties) {
                        var dataRow = $(_CONFIG.JQXGRID).jqxGrid('getrowdata', row);
                        var str = '<div style="overflow: hidden; text-overflow: ellipsis; padding-bottom: 4px; text-align: left; margin-right: 2px; margin-left: 4px; padding-top: 4px;">';
                        str += '<span style="padding-left:' + dataRow.Level * 16 + 'px;">' + value + '</span>';
                        //str+=dataRow.Display;
                        str += '</div>';
                        return str;
                    }
                },
                {
                    text: 'Thumb', dataField: 'Thumb', width: 60,
                    filterable: false, sortable: false, editable: false,
                    cellsrenderer: function(row, columnfield, value, defaulthtml, columnproperties) {
                        if (value === undefined || value === '')
                            return '';
                        else {

                            return '<img onError="this.src = \'/libraries/images/22/picture.png\'" class="cellthumb" height="32" src="' + value + '"/>';
                        }
                    }
                },
                {
                    text: 'Parent', dataField: 'Parent', columntype: 'template', minWidth: 160,
                    cellsrenderer: function(row, columnfield, value, defaulthtml, columnproperties) {
                        var dataRow = $(_CONFIG.JQXGRID).jqxGrid('getrowdata', row);
                        var str = '<div style="overflow: hidden; text-overflow: ellipsis; padding-bottom: 4px; text-align: left; margin-right: 2px; margin-left: 4px; padding-top: 4px;">';
                        var display = value;
                        display = dataRow.ParentTitle;
                        str += display;
                        str += '</div>';
                        return str;
                    },
                    createeditor: function(row, cellvalue, editor, cellText, width, height) {
                        // construct the editor. 
                        editor.jqxDropDownList({
                            //checkboxes: true,
                            source: dataAdapter.records, displayMember: "Display", valueMember: "Id",
                            width: width, height: height, theme: theme,
//                            selectionRenderer: function() {
//                                return "Please Choose:";
//                            }
                        });
                        editor.jqxDropDownList('insertAt', {label: 0, value: 0}, 0);
                        editor.jqxDropDownList('getItem', 0).label = "Root";
                    },
                    initeditor: function(row, cellvalue, editor, celltext, pressedkey) {
                        try {
                            editor.jqxDropDownList('clearSelection');
                            var items = editor.jqxDropDownList('getItems');
                            var dataRow = $(_CONFIG.JQXGRID).jqxGrid('getrowdata', row);
                            var mylevel = -1;
                            for (var i = 0; i < items.length; i++) {
                                if (items[i].value === cellvalue) {
                                    editor.jqxDropDownList('selectItem', items[i]);
                                }
                                var str_action = 'enableItem';
                                if (mylevel >= 0) {
                                    if (items[i].originalItem.Level > mylevel) {
                                        str_action = 'disableItem';//editor.jqxDropDownList('disableItem', items[i]);
                                    } else {
                                        mylevel = -1;
                                    }
                                }
                                if (items[i].value === dataRow.Id) {
                                    mylevel = items[i].originalItem.Level;
                                    str_action = 'disableItem';//editor.jqxDropDownList('disableItem', items[i]);
                                }
                                editor.jqxDropDownList(str_action, items[i]);
                            }
                        } catch (e) {
                            $.jGrowl(e.message, {sticky: true, theme: 'growl-error', header: 'Error!'});
                        }
                    },
                    geteditorvalue: function(row, cellvalue, editor) {
                        // return the editor's value.
                        return editor.val();
                    }
                },
                {
                    text: 'Position', dataField: 'Position',
                    width: 60, cellsalign: 'right',
                    filterable: false, sortable: false, editable: true,
                    columntype: 'numberinput', filtertype: 'number',
                    validation: function(cell, value) {
                        if (value < 0 || value > 99) {
                            return {result: false, message: "Position should be in the 0-99 interval."};
                        }
                        return true;
                    }
                },
                {
                    text: 'Status', dataField: 'Active', cellsalign: 'center',
                    width: 60, columntype: 'checkbox', threestatecheckbox: false,
                    filterable: false, sortable: false, editable: true
                },
                {
                    text: 'Created', dataField: 'Insert', width: 120, cellsformat: 'yyyy-MM-dd HH:mm:ss',
                    filterable: false, sortable: false, editable: false
                },
                {
                    text: 'Modified', dataField: 'Update', width: 120, cellsformat: 'yyyy-MM-dd HH:mm:ss',
                    filterable: false, sortable: false, editable: false
                }
            ];

            $(_CONFIG.JQXGRID).jqxGrid({
                width: '100%', //autoheight:true,
                //height: '100%',
                source: dataAdapter,
                theme: theme,
                columns: columns,
                selectionmode: 'singlecell',
                editmode: 'dblclick',
                editable: true,
                handlekeyboardnavigation: function(event)
                {
                    var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
                    if (key == 27) {
                        that.cancel = true;
                    }
                },
            }).bind('cellbeginedit', function(event) {
                that.cancel = false;
            }).bind('cellendedit', function(event) {
                /* Lưu dữ liệu khi chỉnh sửa trên lưới */
                if (that.cancel)
                    return;
                /* Lưu dữ liệu khi chỉnh sửa trên lưới */
                try {
                    var args = event.args;
                    var column = args.datafield, _row = args.rowindex, _value = args.value;
                    var _data = $(_CONFIG.JQXGRID).jqxGrid('getrowdata', _row);
                    var _id = _data.Id;
                    if (_id == undefined || _id == "") {
                        return;
                    }
                    switch (column) {
                        case 'Title':
                            if (_value != _data.Title && _value != '')
                                _CP.onCommit({Title: _value}, _id);
                            break;
                        case 'Parent':
                            if (_value != _data.Parent)
                                _CP.onCommit({Parent: _value}, _id, function() {
                                    _CP.onRefresh();
                                });
                            break;
                        case 'Position':
                            if (_value != _data.Position)
                                _CP.onCommit({Position: _value}, _id);
                            break;
                        case 'Active':
                            if (_value)
                                _CP.onCommit({Active: 'true'}, _id);
                            else
                                _CP.onCommit({Active: 'false'}, _id);
                            break;
                        default:
                            $.jGrowl("Chưa mở tính năng sửa trực tiếp cột này", {sticky: true, theme: 'growl-error', header: 'Error!'});
                    }
                } catch (e) {
                    $.jGrowl(e.message, {sticky: true, theme: 'growl-error', header: 'Error!'});
                    //bckdialog({type:'error'}).open(e.message);
                }
            });
        },
        onInit: function() {
            this.creategrid();
        },
        onAddItem: function() {
            this.onEditItem(0);
        },
        onEditItem: function(Id) {
            if (PENDING)
                return false;
            $('#dialog-edit-panel>.base-dialog-modal').html('<div class="base_loading" style="display: block;height: 60px"></div>');
            bckdialog({
                title: 'Menu',
                message: $('#dialog-edit-panel'),
                buttons: [
                    {
                        text: 'Done',
                        class: 'base_button base_green base-small-border-radius',
                        click: function() {
                            _CP.onSave();
                        }
                    },
                    {
                        text: 'Close',
                        class: 'base_button base_red base-small-border-radius',
                        click: function() {
                            $(this).dialog("close");
                        }
                    }
                ]
            }).open();
            backend({
                url: _CONFIG.EDITPANEL_URI + _CONFIG.TYPE,
                data: {
                    Id: Id
                },
                callback: function(rsdata) {
                    if (rsdata.result < 0) {
                        $('#dialog-edit-panel>.base-dialog-modal').html('<span style="color:red">' + rsdata.message + '</span>');
                    } else {
                        $('#dialog-edit-panel>.base-dialog-modal').html(rsdata.htmlreponse);
                        $('#dialog-edit-panel').dialog('close').dialog('open');
                        $('#_form_edit_panel select').select2();
                    }
                }
            }).call();
        },
        onSave: function() {
            if ($('#_form_edit_panel').validationEngine('validate') === false)
                return false;
            var Params = $('#_form_edit_panel').serializeObject();
            $("#dialog-edit-panel").parents('.ui-dialog').find('.dialog-pending').show();
            this.onCommit(Params, $('#Id').val(), function() {
                $("#dialog-edit-panel").parents('.ui-dialog').find('.dialog-pending').hide();
                _CP.onRefresh();
                _CP.onCancel();
            });
            return false;
        },
        onCancel: function() {
            $('#dialog-edit-panel').dialog('close');
        },
        onDeleteItem: function(Id) {
            backend_delete(_CONFIG.DELETE_URI, Id, function() {
                _CP.onRefresh();
            });
        },
        onRefresh: function() {
            $(_CONFIG.JQXGRID).jqxGrid('updatebounddata');
        },
        onChangeSource: function(type) {
			if(type===_CONFIG.TYPE)return;
            _CONFIG.TYPE = type;
            source.url = _CONFIG.BINDING_URI + _CONFIG.TYPE;
            this.onRefresh();
        }
    };
}());